package com.talkweb.citypickerview.style.cityjd;

import com.talkweb.citypickerview.ResourceTable;
import com.talkweb.citypickerview.bean.CityBean;
import ohos.agp.components.*;
import ohos.app.Context;
import java.util.List;


public class CityAdapter extends BaseItemProvider {

    Context context;

    List<CityBean> mCityList;

    private int cityIndex = JDConst.INDEX_INVALID;

    public CityAdapter(Context context, List<CityBean> mCityList) {
        this.context = context;
        this.mCityList = mCityList;
    }

    public int getSelectedPosition() {
        return this.cityIndex;
    }

    public void updateSelectedPosition(int index) {
        this.cityIndex = index;
    }

    @Override
    public int getCount() {
        return mCityList.size();
    }

    @Override
    public CityBean getItem(int position) {
        return mCityList.get(position);
    }


    @Override
    public long getItemId(int position) {
        return Long.parseLong(mCityList.get(position).getId());
    }

    @Override
    public Component getComponent(int position, Component convertView, ComponentContainer parent) {
        Holder holder;

        if (convertView == null) {
            convertView = LayoutScatter.getInstance(parent.getContext()).parse(ResourceTable.Layout_pop_jdcitypicker_item, parent, false);

            holder = new Holder();
            holder.name = (Text) convertView.findComponentById(ResourceTable.Id_name);
            holder.selectImg = (Image) convertView.findComponentById(ResourceTable.Id_selectImg);

            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }

        CityBean item = getItem(position);
        holder.name.setText(item.getName());

        boolean checked = cityIndex != JDConst.INDEX_INVALID && mCityList.get(cityIndex).getName().equals(item.getName());
        holder.name.setEnabled(!checked);
        holder.selectImg.setVisibility(checked ? Component.VISIBLE : Component.HIDE);


        return convertView;
    }


    class Holder {
        Text name;
        Image selectImg;
    }
}
